package com.bsb.biz.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.bsb.base.common.config.WithdrawStatus;
import com.bsb.base.common.util.BeanUtils;
import com.bsb.base.common.util.StringUtils;
import com.bsb.base.common.util.UmengPushUtil;
import com.bsb.base.model.BsbUser;
import com.bsb.base.model.BsbWithdraw;
import com.bsb.base.model.BsbWithdrawExample;
import com.bsb.base.model.BsbWithdrawExample.Criteria;
import com.bsb.base.model.Withdraw;
import com.bsb.biz.service.BsbUserService;
import com.bsb.biz.service.BsbWithdrawService;

@Controller
@RequestMapping("/bsbWithdraw")
public class BsbWithdrawController{
	
	private int defaultPageSize=10;
	
	private String redirect = "redirect:/bsbWithdraw/list.do";
	
	@Resource
	private BsbWithdrawService bsbWithdrawService;
	@Resource
	private BsbUserService bsbUserService;
	
	@RequiresPermissions("bsbWithdraw:view")
	@RequestMapping(value="/list",method = RequestMethod.GET)
	public String list(
			Model model,String status,String phone,
			@RequestParam(value = "pageNum", required = false) Integer pageNum,
			@RequestParam(value = "pageSize", required = false) Integer pageSize) {
		int maxPageNum = 0;
		if (pageSize == null) {
			pageSize = defaultPageSize;
		}
		BsbWithdrawExample bsbWithdrawExample = new BsbWithdrawExample();
		Criteria criteria = bsbWithdrawExample.createCriteria();
		if(StringUtils.isNotEmpty(status)){
			criteria.andStatusEqualTo(status);
		}
		if(StringUtils.isNotEmpty(phone)){
			BsbUser userByPhone = bsbUserService.getUserByPhone(phone);
			if(null != userByPhone){
				String uuid = userByPhone.getUuid();
				criteria.andUseridEqualTo(uuid);
			}
		}
		int totalCount = bsbWithdrawService.countBsbWithdraw(bsbWithdrawExample);
		if(totalCount%pageSize == 0){
			maxPageNum = totalCount/pageSize;
		}else{
			maxPageNum = totalCount/pageSize+1;
		}
		if (pageNum == null || pageNum < 1) {
			pageNum = 1;
		}else {
			if(maxPageNum > 0 && pageNum > maxPageNum) {
				pageNum = maxPageNum;
			}
		}
		bsbWithdrawExample.setPageIndex((pageNum - 1) * pageSize);
		bsbWithdrawExample.setPageSize(pageSize);
		bsbWithdrawExample.setOrderByClause("createDate DESC");
		List<BsbWithdraw> bsbWithdraws = bsbWithdrawService.getPageBsbWithdraw(bsbWithdrawExample);
		List<Withdraw> list = new ArrayList<Withdraw>();
		for (BsbWithdraw bsbWithdraw : bsbWithdraws) {
			Withdraw with = new Withdraw();
			String userid = bsbWithdraw.getUserid();
			BsbUser bsbUserByUuid = bsbUserService.getBsbUserByUuid(userid);
			BeanUtils.copyProperties(with, bsbWithdraw);
			if(null != bsbUserByUuid){
				with.setNickname(bsbUserByUuid.getName());;
				with.setPhone(bsbUserByUuid.getPhone());
				with.setRole(bsbUserByUuid.getRole());
			}
			list.add(with);
		}
		model.addAttribute("totalCount", totalCount);
		model.addAttribute("pageNum", pageNum);
		model.addAttribute("pageSize", pageSize);
		if(totalCount%pageSize == 0){
			model.addAttribute("maxPageNum", totalCount/pageSize);
		}else{
			model.addAttribute("maxPageNum", totalCount/pageSize+1);
		}
		List<WithdrawStatus> selects = WithdrawStatus.getList();
		model.addAttribute("status", status);
		model.addAttribute("phone", phone);
		model.addAttribute("selects", selects);
		model.addAttribute("bsbWithdraws", list);
		return "/BsbWithdraw/list";
	}
	
	@RequiresPermissions("bsbWithdraw:create")
	@RequestMapping(value = "/create", method = RequestMethod.GET)
	public String toAdd(Model model) {
		return "/BsbWithdraw/add";
	}

	@RequiresPermissions("bsbWithdraw:create")
	@RequestMapping(value = "/create", method = RequestMethod.POST)
	public String add(Model model, @ModelAttribute("bsbWithdraw") BsbWithdraw bsbWithdraw) {
		bsbWithdrawService.addBsbWithdraw(bsbWithdraw);
		return redirect;
	}
	
	@RequiresPermissions("bsbWithdraw:delete")
	@RequestMapping(value = "/{uuid}/delete", method = RequestMethod.GET)
	public String del(Model model,
			@PathVariable("uuid") String uuid) {
		bsbWithdrawService.delBsbWithdrawByUuid(uuid);
		return redirect;
	}
	
	@RequiresPermissions("bsbWithdraw:update")
	@RequestMapping(value = "/{uuid}/update", method = RequestMethod.GET)
	public String toEdit(Model model,
			@PathVariable("uuid") String uuid) {
		BsbWithdraw bsbWithdraw = bsbWithdrawService.getBsbWithdrawByUuid(uuid);
		model.addAttribute("bsbWithdraw", bsbWithdraw);
		return "/BsbWithdraw/edit";
	}

	@RequiresPermissions("bsbWithdraw:update")
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public String edit(Model model, @ModelAttribute("bsbWithdraw") BsbWithdraw bsbWithdraw) {
		bsbWithdrawService.updateBsbWithdraw(bsbWithdraw);
		return redirect;
	}
	@RequiresPermissions("bsbWithdraw:check")
	@RequestMapping(value = "/{uuid}/check", method = RequestMethod.GET)
	public String toCheck(Model model,
			HttpServletRequest request,RedirectAttributes redirectAttributes,
			@PathVariable("uuid") String uuid) {
		BsbWithdraw bsbWithdraw = bsbWithdrawService.getBsbWithdrawByUuid(uuid);
		String queryString = request.getQueryString();
		String statusself = bsbWithdraw.getStatus();
		if(!WithdrawStatus.PENDINGCHECK.getIndex().equals(statusself)){
			redirectAttributes.addFlashAttribute("msg", "该条数据已经审核过不能再次审核!");
			return redirect + "?" +queryString;
		}
		Withdraw with = new Withdraw();
		String userid = bsbWithdraw.getUserid();
		BsbUser bsbUserByUuid = bsbUserService.getBsbUserByUuid(userid);
		BeanUtils.copyProperties(with, bsbWithdraw);
		if(null != bsbUserByUuid){
			with.setNickname(bsbUserByUuid.getName());;
			with.setPhone(bsbUserByUuid.getPhone());
			with.setRole(bsbUserByUuid.getRole());
		}
		model.addAttribute("bsbWithdraw", with);
		model.addAttribute("queryString", queryString);
		return "/BsbWithdraw/check";
	}
	
	@RequiresPermissions("bsbWithdraw:check")
	@RequestMapping(value = "/{uuid}/check", method = RequestMethod.POST)
	public String check(Model model, 
			RedirectAttributes redirectAttributes,
			@PathVariable("uuid") String uuid,
			@RequestParam(value="queryString",required=false) String queryString,
			@RequestParam(value="status",required=true) String status,
			@RequestParam(value="reason",required=false) String reason) throws Exception {
		BsbWithdraw bsbWithdrawByUuid = bsbWithdrawService.getBsbWithdrawByUuid(uuid);
		if(StringUtils.isEmpty(queryString)){
			queryString = "";
		}
		if(null == bsbWithdrawByUuid){
			return redirect + "?" +queryString;
		}
		String statusself = bsbWithdrawByUuid.getStatus();
		if(!WithdrawStatus.PENDINGCHECK.getIndex().equals(statusself)){
			redirectAttributes.addFlashAttribute("msg", "该条数据已经审核过不能再次审核!");
			return redirect + "?" +queryString;
		}
		String userid = bsbWithdrawByUuid.getUserid();
		String title = "您的提现申请已通过，到账时间根据银行而定。";
		String type = "11";
		Map<String , String> map = new HashMap<String , String>();
		map.put("type", type);
		
		if(WithdrawStatus.PENDINGCHECK.getIndex().equals(statusself) && WithdrawStatus.PASS.getIndex().equals(status)){
			//审核通过
			BsbWithdraw bsbWithdraw = new BsbWithdraw();
			bsbWithdraw.setUuid(uuid);
			bsbWithdraw.setStatus(WithdrawStatus.PASS.getIndex());
			bsbWithdraw.setUpdateid((String)SecurityUtils.getSubject().getPrincipal());
			bsbWithdrawService.updateBsbWithdraw(bsbWithdraw);
			//先修改状态为审核通过再去给微信发送请求
			try {
				bsbWithdrawService.updatePass(uuid);
				map.put("type", type);
				UmengPushUtil.sendAndroidCustomizedcast(title , userid, map);
				UmengPushUtil.sendIOSCustomizedcast(title, userid, map);
			} catch (Exception e) {
				e.printStackTrace();
				BsbWithdraw draw = new BsbWithdraw();
				draw.setUuid(uuid);
				draw.setStatus(WithdrawStatus.EXCEPTION.getIndex());
				draw.setUpdateid((String)SecurityUtils.getSubject().getPrincipal());
				draw.setRemarks(e.getMessage());
				bsbWithdrawService.updateBsbWithdraw(draw);
				redirectAttributes.addFlashAttribute("msg", e.getMessage());
				title = "很抱歉，您的提现申请异常，请查看。";
				UmengPushUtil.sendAndroidCustomizedcast(title , userid, map);
				UmengPushUtil.sendIOSCustomizedcast(title, userid, map);
			}
		}else if(WithdrawStatus.PENDINGCHECK.getIndex().equals(statusself) && WithdrawStatus.NOPASS.getIndex().equals(status)){
			//审核不通过
			if(StringUtils.isEmpty(reason)){
				redirectAttributes.addFlashAttribute("msg", "不通过理由不能为空!");
				return redirect + "?" +queryString;
			}
			bsbWithdrawService.updateNopass(uuid,reason);
			title = "很抱歉，您的提现申请未通过，请查看。";
			UmengPushUtil.sendAndroidCustomizedcast(title , userid, map);
			UmengPushUtil.sendIOSCustomizedcast(title, userid, map);
		}else{
			redirectAttributes.addFlashAttribute("msg", "数据异常，请联系管理员!");
			return redirect + "?" +queryString;
		}
		return redirect + "?" +queryString;
	}
	
	@RequiresPermissions("bsbWithdraw:view")
	@RequestMapping(value = "/{uuid}/view", method = RequestMethod.GET)
	public String view(Model model,
			@PathVariable("uuid") String uuid) {
		BsbWithdraw bsbWithdraw = bsbWithdrawService.getBsbWithdrawByUuid(uuid);
		Withdraw with = new Withdraw();
		String userid = bsbWithdraw.getUserid();
		BsbUser bsbUserByUuid = bsbUserService.getBsbUserByUuid(userid);
		BeanUtils.copyProperties(with, bsbWithdraw);
		if(null != bsbUserByUuid){
			with.setNickname(bsbUserByUuid.getName());;
			with.setPhone(bsbUserByUuid.getPhone());
			with.setRole(bsbUserByUuid.getRole());
		}
		model.addAttribute("bsbWithdraw", with);
		return "/BsbWithdraw/view";
	}
}
